<template>
  <!-- 宠物档案 -->
  <view class="mainBox">
    <!-- 基本信息 -->
    <view class="basicInfo">
      <!-- <view class="title1"> 宠物信息 </view> -->
      <view class="basicInfoBox">
        <view class="petInfoBox lineBox">
          <view class="leftPetImg">
            <view class="noImg" v-if="form.mediaList">
              <image
                :src="
                  form.mediaList[0]
                    ? form.mediaList[0]
                    : '/static/activity/icon_upload.png'
                "
                @click="uploadImg"
                mode="aspectFit"
              ></image>
            </view>
            <image
              v-else
              :src="form.author"
              @click="uploadImg"
              mode="aspectFit"
            ></image>
            <!-- <image :src="form.author?form.author:'/static/activity/icon_upload.png'"
							@click="uploadImg" mode="aspectFit"></image>
						<view style="text-align: center;font-size: 10px;margin-top: -13%;" v-if="!form.author">请上传宠物头像
						</view> -->
            <!-- <image src="/static/my/pet.png" mode="aspectFit" @click=""></image> -->
          </view>
          <view class="rightBox">
            <view class="form-header lineBox">
              <text class="title">基本信息</text>
            </view>

            <view class="form-item lineBox">
              <text class="form-title">姓名：</text>
              <input
                type="text"
                class="form-input"
                placeholder="点击填写"
                v-model="form.name"
              />
            </view>

            <view class="form-item lineBox">
              <text class="form-title">性别：</text>
              <uni-data-select
                v-model="form.gender"
                placeholder="点击填写"
                :localdata="gender"
                @change="change"
              ></uni-data-select>
            </view>

            <view class="form-item lineBox">
              <text class="form-title">年龄：</text>
              <view class="from-right" style="text-align: right">
                <input
                  class="form-input"
                  type="number"
                  placeholder="点击填写"
                  v-model="form.age"
                />
                <!--<view class="form-title" style="text-align: right;">约等于人的32岁</view>-->
              </view>
            </view>

            <view class="form-item lineBox">
              <text class="form-title">出生日期：</text>
              <!-- @change="change" -->
              <picker mode="date" @change="bindDateChange">
                <view class="uni-input">{{ form.birthDate || "请选择" }}</view>
              </picker>
            </view>

            <view class="form-item lineBox">
              <text class="form-title">品种：</text>
              <input
                type="text"
                class="form-input"
                placeholder="点击填写"
                v-model="form.breed"
              />
            </view>
          </view>
        </view>
        <view class="form-bottom">
          <view class="form-item">
            <text class="form-title">最新身价：</text>
            <input
              type="text"
              class="form-input left"
              placeholder="—"
              v-model="form.latestValue"
            />
          </view>
          <view class="form-item">
            <text class="form-title">已陪伴：</text>
            <input
              type="text"
              class="form-input left"
              placeholder="—"
              v-model="form.accompanyDays"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 身体数据概况 -->
    <view class="form">
      <view class="title1"> 身体数据概况 </view>
      <view class="formBox">
        <view class="form-item lineBox">
          <view class="form-item w300">
            <text class="form-title">体重：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.weight"
            />
          </view>
          <view class="form-item w300">
            <text class="form-title">腿长：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.legLength"
            />
          </view>
        </view>
        <view class="form-item lineBox">
          <view class="form-item w300">
            <text class="form-title">头围：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.headCircumference"
            />
          </view>
          <view class="form-item w300">
            <text class="form-title">尾长：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.tailLength"
            />
          </view>
        </view>
        <view class="form-item lineBox">
          <view class="form-item w300">
            <text class="form-title">腰围：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.waistCircumference"
            />
          </view>
          <view class="form-item w300">
            <text class="form-title">爪子颜色：</text>
            <input
              type="text"
              class="form-input"
              placeholder="点击填写"
              v-model="form.pawColor"
            />
          </view>
        </view>
        <view class="form-item lineBox">
          <view class="form-item w300">
            <text class="form-title">颈围：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.neckCircumference"
            />
          </view>
          <view class="form-item w300">
            <text class="form-title">眼睛颜色：</text>
            <input
              type="text"
              class="form-input"
              placeholder="点击填写"
              v-model="form.eyeColor"
            />
          </view>
        </view>
        <view class="form-item lineBox">
          <view class="form-item w300">
            <text class="form-title">身长：</text>
            <input
              type="number"
              class="form-input"
              placeholder="点击填写"
              v-model="form.bodyLength"
            />
          </view>
          <view class="form-item w300">
            <text class="form-title">是否绝育：</text>
            <uni-data-select
              v-model="form.isSpayed"
              placeholder="点击填写"
              :localdata="isSpayed"
              @change="change"
            ></uni-data-select>
          </view>
        </view>
        <view class="form-item lineBox">
          <view class="form-item w300">
            <text class="form-title">接种疫苗情况：</text>
            <input
              type="text"
              class="form-input"
              placeholder="点击填写"
              v-model="form.vaccineSituation"
            />
          </view>
        </view>
      </view>
    </view>
    <!-- 性格行为习惯展示 -->
    <view class="natureBox">
      <view class="title1"> 性格行为习惯展示 </view>
      <view class="natureText">
        <textarea
          name=""
          id=""
          cols="30"
          rows="10"
          v-model="form.personalityHabit"
          placeholder="点击填写"
        ></textarea>
      </view>
    </view>
    <!-- 可见范围 -->
    <view class="selectBox">
      <view class="selectBoxItem" @click="switchSelect(1)">
        <image
          v-if="selectVal == 1"
          src="/static/my/selectIcon.png"
          mode="aspectFit"
        ></image>
        <image
          v-if="selectVal == 2"
          src="/static/my/noSelectIcon.png"
          mode="aspectFit"
        ></image>
        <text>对所有人可见</text>
      </view>
      <view class="selectBoxItem" @click="switchSelect(2)">
        <image
          v-if="selectVal == 2"
          src="/static/my/selectIcon.png"
          mode="aspectFit"
        ></image>
        <image
          v-if="selectVal == 1"
          src="/static/my/noSelectIcon.png"
          mode="aspectFit"
        ></image>
        <text>仅自己可见</text>
      </view>
    </view>

    <view class="btn">
      <button @click="save">保存</button>
    </view>
  </view>
</template>

<script>
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  data() {
    return {
      show: true,
      selectVal: 1,
      form: {
        files: [],
      },
      petId: null,
      gender: [
        {
          value: 1,
          text: "公",
        },
        {
          value: 2,
          text: "母",
        },
      ],
      isSpayed: [
        {
          value: 0,
          text: "否",
        },
        {
          value: 1,
          text: "是",
        },
      ],
    };
  },
  onLoad(options) {
    if (options.petId) {
      this.petId = options.petId;
      this.getData();
    }
  },
  methods: {
    bindDateChange(e) {
      this.form.birthDate = e.detail.value;
      console.log(e, "sss");
    },
    uploadImg() {
      let that = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          var file = res.tempFiles[0];
          if (file.size > 2 * (1024 * 1024)) {
            uni.app.msg("图片尺寸过大，已忽略");
            return;
          }
          console.log(file);
          //拿到数据后上传
          uni.uploadFile({
            url: this.$uploadUrl,
            filePath: file.path,
            name: file.fileName,
            formData: {
              fileSavePath: "/background",
            },
            success: (uploadRes) => {
              try {
                uploadRes = JSON.parse(uploadRes.data);
                that.form.mediaList[0] = uploadRes.data;
                uni.showToast({
                  title: uploadRes.message,
                  icon: "none",
                });
              } catch (e) {
                this.error(index);
              }
            },
            fail: (e) => {
              uni.showToast({
                title: "上传失败，请点击图片重试",
                icon: "none",
              });
            },
          });
        },
        complete: function () {},
      });
    },

    switchSelect(val) {
      this.selectVal = val;
    },
    getData() {
      uni.app.post(
        "/pet/info/getInfos",
        {
          id: this.petId,
          userId: uni.getStorageSync("userId"),
          limit: 1,
          offset: 1,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            this.form = {
              ...res.data.records[0],
              files: this.form.files || [], // 保持 files 数组
            };
            console.log(this.form);
          }
        },
      );
    },
    goBack() {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          window.AndroidBridge.backEvent();
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.backEvent.postMessage({});
          break;
        default:
          console.log("运行在开发者工具上");
          uni.navigateBack({
            delta: 1,
          });
          break;
      }
    },
    save() {
      // 表单验证 - 检查所有必填项
      if (!this.form.mediaList) {
        uni.showToast({
          title: "请上传宠物头像",
          icon: "none",
        });
        return;
      }

      if (!this.form.name || this.form.name.trim() === "") {
        uni.showToast({
          title: "请填写宠物姓名",
          icon: "none",
        });
        return;
      }

      if (!this.form.gender && this.form.gender !== 0) {
        uni.showToast({
          title: "请选择宠物性别",
          icon: "none",
        });
        return;
      }

      if (!this.form.age || this.form.age <= 0) {
        uni.showToast({
          title: "请填写宠物年龄",
          icon: "none",
        });
        return;
      }

      if (!this.form.birthDate) {
        uni.showToast({
          title: "请选择宠物出生日期",
          icon: "none",
        });
        return;
      }

      if (!this.form.breed || this.form.breed.trim() === "") {
        uni.showToast({
          title: "请填写宠物品种",
          icon: "none",
        });
        return;
      }

      if (!this.form.weight || this.form.weight <= 0) {
        uni.showToast({
          title: "请填写宠物体重",
          icon: "none",
        });
        return;
      }

      if (!this.form.isSpayed && this.form.isSpayed !== 0) {
        uni.showToast({
          title: "请选择是否绝育",
          icon: "none",
        });
        return;
      }

      // 身体数据概况验证
      if (!this.form.legLength || this.form.legLength <= 0) {
        uni.showToast({
          title: "请填写腿长",
          icon: "none",
        });
        return;
      }

      if (!this.form.headCircumference || this.form.headCircumference <= 0) {
        uni.showToast({
          title: "请填写头围",
          icon: "none",
        });
        return;
      }

      if (!this.form.tailLength || this.form.tailLength <= 0) {
        uni.showToast({
          title: "请填写尾长",
          icon: "none",
        });
        return;
      }

      if (!this.form.waistCircumference || this.form.waistCircumference <= 0) {
        uni.showToast({
          title: "请填写腰围",
          icon: "none",
        });
        return;
      }

      if (!this.form.pawColor || this.form.pawColor.trim() === "") {
        uni.showToast({
          title: "请填写爪子颜色",
          icon: "none",
        });
        return;
      }

      if (!this.form.neckCircumference || this.form.neckCircumference <= 0) {
        uni.showToast({
          title: "请填写颈围",
          icon: "none",
        });
        return;
      }

      if (!this.form.eyeColor || this.form.eyeColor.trim() === "") {
        uni.showToast({
          title: "请填写眼睛颜色",
          icon: "none",
        });
        return;
      }

      if (!this.form.bodyLength || this.form.bodyLength <= 0) {
        uni.showToast({
          title: "请填写身长",
          icon: "none",
        });
        return;
      }

      if (
        !this.form.vaccineSituation ||
        this.form.vaccineSituation.trim() === ""
      ) {
        uni.showToast({
          title: "请填写接种疫苗情况",
          icon: "none",
        });
        return;
      }

      // 其他可选字段验证
      if (!this.form.latestValue || this.form.latestValue === "") {
        uni.showToast({
          title: "请填写最新身价",
          icon: "none",
        });
        return;
      }

      if (!this.form.accompanyDays || this.form.accompanyDays === "") {
        uni.showToast({
          title: "请填写已陪伴天数",
          icon: "none",
        });
        return;
      }

      if (
        !this.form.personalityHabit ||
        this.form.personalityHabit.trim() === ""
      ) {
        uni.showToast({
          title: "请填写性格行为习惯",
          icon: "none",
        });
        return;
      }

      // 确保 files 数组存在
      if (!this.form.files) {
        this.form.files = [];
      }

      this.form = {
        ...this.form,
        userId: uni.getStorageSync("userId"),
        files: [...(this.form.files || [])], // 保持 files 数组
      };
      this.form.files.push(this.form.mediaList[0]);

      // 根据是否有 petId 判断是新增还是修改
      const apiUrl = this.petId ? "/pet/info/updateInfo" : "/pet/info/addInfo";
      const successMessage = this.petId ? "宠物信息修改成功" : "宠物添加成功";

      uni.app.post(apiUrl, this.form, "json", "", (res) => {
        if (res.code == 2000) {
          uni.showToast({
            title: successMessage,
            icon: "none",
          });
          // 使用 app 方法返回上一页
          this.goBack();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.noImg {
  height: 400rpx;

  image {
    height: 100%;
    height: 100%;
  }
}

page {
  background-color: #f8f8f8;
}

.basicInfo {
  margin: 0 28rpx;

  .basicInfoBox {
    padding: 32rpx;
    background-color: #ffffff;
  }
}

.natureBox {
  margin: 0 28rpx;
}

.selectBox {
  margin: 0 28rpx;
}

.petInfoBox {
  display: flex;
  align-items: top;
}

.form-header {
  padding: 0 0 15rpx;
}

.form-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 15rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;

  .form-title {
    font-weight: 500;
    font-size: 24rpx;
    color: #7f7f7f;
  }

  .form-input {
    flex: 1;
    font-size: 26rpx;
    color: #303030;
    text-align: right;

    &.left {
      text-align: left;
    }
  }

  .from-right {
    flex: 1;
  }

  &:last-child {
    border-bottom: none;
  }
}

.lineBox {
  border-bottom: 2rpx solid #f8f8f8;
}

.w300 {
  width: 300rpx;
}

.leftPetImg {
  width: 300rpx;
  height: 402rpx;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
}

.leftPetImg image {
  width: 100%;
  height: 100%;
}

.rightBox {
  flex: 1;
  margin-left: 32rpx;
}

.title {
  font-weight: bold;
  font-size: 30rpx;
  color: #303030;
  line-height: 40rpx;
}

.title1 {
  margin: 48rpx 0 16rpx;
  font-weight: bold;
  font-size: 30rpx;
  color: #303030;
  line-height: 40rpx;
  text-align: center;
}

.editTextImg {
  width: 80rpx;
  height: 34rpx;
}

.natureText {
  font-weight: bold;
  font-size: 26rpx;
  color: #303030;
  background-color: #ffffff;
  padding: 32rpx;
}

.formBox {
  background-color: #ffffff;
  padding: 34rpx 32rpx;
  margin: 0 28rpx;
}

.selectBox {
  display: flex;
  align-items: center;
  margin-top: 34rpx;
  padding-bottom: 200rpx;

  .selectBoxItem {
    display: flex;
    align-items: center;
    margin-right: 96rpx;

    image {
      width: 32rpx;
      height: 32rpx;
      margin-right: 16rpx;
    }

    text {
      font-weight: 400;
      font-size: 24rpx;
      color: #666666;
    }
  }
}

.btn {
  background: #ffffff;
  position: fixed;
  width: 100%;
  bottom: 0;
  padding: 20rpx 0;

  button {
    width: 90%;
    height: 60rpx;
    line-height: 60rpx;
    border: none;
    border-radius: 50px;
    background: #daf600;
  }
}
</style>
